package com.think.admin.oauth.integration;

import com.think.admin.oauth.integration.authenticator.IntegrationAuthenticator;
import com.think.common.utils.SysUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 认证服务类
 * </p>
 *
 * @author: xwj
 * @data: 2019-05-11
 */
@Service
@RequiredArgsConstructor
public class IntegrationAuthenticationService implements UserDetailsService {
    private final List<IntegrationAuthenticator> authenticators;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //判断是否是集成登录
        IntegrationAuthentication integrationAuthentication = IntegrationAuthenticationContext.get();
        if (SysUtils.isEmpty(integrationAuthentication)) {
            integrationAuthentication = new IntegrationAuthentication();
        }

        // 执行认证
        integrationAuthentication.setUsername(username);
        UserDetails userDetails = this.authenticate(integrationAuthentication);
        if(SysUtils.isEmpty(userDetails)){
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        // 返回
        return userDetails;
    }

    /***
     * 认证
     *
     * @param integrationAuthentication 
     * @return org.springframework.security.core.userdetails.UserDetails
     * @author xwj
     * @data 2019/5/11
     */
    private UserDetails authenticate(IntegrationAuthentication integrationAuthentication) {
        if (this.authenticators != null) {
            for (IntegrationAuthenticator authenticator : authenticators) {
                if (authenticator.support(integrationAuthentication)) {
                    return authenticator.authenticate(integrationAuthentication);
                }
            }
        }
        return null;
    }
}
